package com.cqhilink.iot.jobstandardmanagement.services.innerservice.impl.singlework;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cqhilink.api.common.utils.StringUtil;
import com.cqhilink.api.common.utils.UniqueUtil;
import com.cqhilink.api.common.utils.date.DateStyle;
import com.cqhilink.api.common.utils.date.DateUtil;
import com.cqhilink.api.common.utils.enums.RespCodeEnum;
import com.cqhilink.iot.jobstandardmanagement.dao.mapper.ReportItemMapper;
import com.cqhilink.iot.jobstandardmanagement.facade.utils.BackMessage;
import com.cqhilink.iot.jobstandardmanagement.facade.utils.StepStage;
import com.cqhilink.iot.jobstandardmanagement.facade.utils.poi.ExcelUtil;
import com.cqhilink.iot.jobstandardmanagement.dao.mapper.EntityMapper;
import com.cqhilink.iot.jobstandardmanagement.dao.mapper.SingleWorkStepDataItemMapper;
import com.cqhilink.iot.jobstandardmanagement.dao.mapper.SingleWorkStepMapper;
import com.cqhilink.iot.jobstandardmanagement.facade.model.*;
import com.cqhilink.iot.jobstandardmanagement.facade.service.device.JsmDeviceService;
import com.cqhilink.iot.jobstandardmanagement.facade.service.employee.JsmEmployeeService;
import com.cqhilink.iot.jobstandardmanagement.facade.service.file.JsmFileService;
import com.cqhilink.iot.jobstandardmanagement.facade.service.singlework.JsmSingleWorkService;
import com.cqhilink.iot.jobstandardmanagement.facade.service.version.JsmVersionService;
import com.cqhilink.iot.jobstandardmanagement.facade.service.workcellinstance.JsmWorkCellInstanceService;
import org.apache.commons.collections.list.AbstractLinkedList;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by YuPeng on 2016/12/19.
 * 单项工作步骤Service逻辑层
 * modify by huangxueqian 2018-1-2
 */

public class JsmSingleWorkStepServiceImpl implements JsmSingleWorkService {
    public Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private SingleWorkStepMapper stepMapper;
    @Autowired
    private SingleWorkStepDataItemMapper stepDataItemMapper;
    @Autowired
    private JsmWorkCellInstanceService workCellInstanceService;
    @Autowired
    private ReportItemMapper reportItemMapper ;

    @Autowired
    private JsmFileService fileService;

    @Autowired
    private JsmVersionService versionService;

    /**
     * 添加单项步骤
     * 分为正常添加和插入
     *
     * @param singleWorkStep
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public Map<String, Object> add(SingleWorkStep singleWorkStep, Employee employee) throws Exception {
        singleWorkStep.setStepId(UniqueUtil.uuid());
        // Employee employee = employeeService.getLoginEmployee();
        String creatorId = employee.getEmployeeId();
        BigDecimal version = singleWorkStep.getVersion();
        BigDecimal versionWork = getWorkContent(singleWorkStep.getWorkContentId()).getStepVersion();
        if (version == null && versionWork == null) {
            version = new BigDecimal(1);
            stepMapper.updateStepVersion(new WorkCellInstance(singleWorkStep.getWorkContentId(), version));
        }
        //对参数进行判空
        Map<String, Object> map = isBlank(singleWorkStep);
        if ((Boolean) map.get("state") == RespCodeEnum.RESP_CODE_ENUM_false.code()) {
            return map;
        }
        singleWorkStep.setCreatorId(creatorId);
        singleWorkStep.setCreateTime(DateUtil.getTimeString());
        singleWorkStep.setVersion(version);
        if (singleWorkStep.getStepIndex() != null) {
            map = insertStep(singleWorkStep);
        } else {
            map = addStep(singleWorkStep);
        }
        return map;
    }

    /**
     * 正常添加步骤
     *
     * @param singleWorkStep
     * @return
     * @throws Exception
     */
    private Map<String, Object> addStep(SingleWorkStep singleWorkStep) throws Exception {
        Map<String, Object> map = new HashMap<>();
        SingleWorkStep step = new SingleWorkStep(singleWorkStep.getWorkContentId());
        step.setVersion(singleWorkStep.getVersion());
        int maxIndex = stepMapper.selectCountByStep(step);
        singleWorkStep.setStepIndex(maxIndex + 1);
        int num = stepMapper.insertSelective(singleWorkStep);
        map.put("state", num > 0 ? RespCodeEnum.RESP_CODE_ENUM_true.code() : RespCodeEnum.RESP_CODE_ENUM_false.code());
        map.put("msg", num > 0 ? BackMessage.ADD_OK : BackMessage.ADD_FAIL);
        return map;
    }

    /**
     * 用于插入式添加步骤
     *
     * @param singleWorkStep
     * @return
     */
    private Map<String, Object> insertStep(SingleWorkStep singleWorkStep) throws Exception {
        Map<String, Object> map = new HashMap<>();
        String workContentId = singleWorkStep.getWorkContentId();
        int index = singleWorkStep.getStepIndex();
        //获取数据库中已存在该索引的步骤对象
        SingleWorkStep step = stepMapper.selectByStepSelect(new SingleWorkStep(index, workContentId, singleWorkStep.getVersion())).get(0);
        //获取往后的所有步骤
        List<SingleWorkStep> stepList = getAfterSteps(step.getStepId());
        stepList.add(step);
        //将后面的步骤索引+1
        if (udpateIndexDownByList(stepList) > 0) {
            //插入新增的步骤
            if (stepMapper.insertSelective(singleWorkStep) > 0) {
                map.put("state", RespCodeEnum.RESP_CODE_ENUM_true.code());
                map.put("msg", BackMessage.ADD_OK);
                return map;
            }
        }
        map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());
        map.put("msg", BackMessage.ADD_FAIL);
        return map;
    }

    /**
     * 批量步骤下移
     *
     * @param stepList
     * @return
     */
    private Integer udpateIndexDownByList(List<SingleWorkStep> stepList) throws Exception {
        int num = 0;
        if (stepList != null && stepList.size() > 0) {
            for (SingleWorkStep step : stepList) {
                num += stepMapper.updateIndex(step.getStepIndex() + 1, step.getStepId());
            }
        }
        return num;
    }

    /**
     * 导入步骤
     *
     * @param excel
     * @param workInstanceId
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public Map<String, Object> importStep(MultipartFile excel, String workInstanceId, BigDecimal version, Employee employee) throws Exception {
        Map<String, Object> map = new HashMap<>();
        String creatorId = employee.getEmployeeId();
        if (excel.isEmpty()) {
            map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());
            map.put("msg", BackMessage.UPLOAD_PLEASE);
            return map;
        }
        //判断参数version是否为空，如果为空，则是在原来步骤版本中导入，如果不为空，则在新版本中导入
        if (version == null) {
            WorkCellInstance workCellInstance = getWorkContent(workInstanceId);
            version = workCellInstance.getStepVersion();
            if (version == null) {
                version = new BigDecimal(stepMapper.selectLastVersion(workInstanceId));
                if (version == null) {
                    version = new BigDecimal(1);
                    stepMapper.updateStepVersion(new WorkCellInstance(workInstanceId, version));
                }
            }
        }
        //解析EXCEL
        ExcelUtil eu = new ExcelUtil(SingleWorkStep.class);
        List<SingleWorkStep> stepList = new ArrayList<>();
        String suffix = excel.getOriginalFilename().substring(excel.getOriginalFilename().lastIndexOf(".") + 1);//获取上传后缀
        try {
            stepList = eu.importExcel(excel.getInputStream(), suffix);
        } catch (Exception e) {
            map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());
            map.put("msg", BackMessage.INVALID_FILE_FORMAT);
            return map;
        }
        String date = DateUtil.getTimeString();
        int num = 0;
        int currentIndex = getCurrentNum(workInstanceId, version);
        if (stepList != null && stepList.size() > 0) {
            for (SingleWorkStep step : stepList) {
                step.setCreatorId(creatorId);
                step.setCreateTime(date);
                step.setStepId(UniqueUtil.uuid());
                step.setStepIndex(++currentIndex);
                step.setWorkContentId(workInstanceId);
                step.setVersion(version);
                map = isBlank(step);
                if ((Boolean) map.get("state") == RespCodeEnum.RESP_CODE_ENUM_false.code()) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return map;
                }
                num += stepMapper.insertSelective(step);
            }
        }
        map.put("state", num > 0 ? RespCodeEnum.RESP_CODE_ENUM_true.code() : RespCodeEnum.RESP_CODE_ENUM_false.code());
        map.put("msg", num > 0 ? BackMessage.IMPORT_OK : BackMessage.IMPORT_FAIL);
        return map;
    }

    /**
     * 修改单项步骤
     *
     * @param singleWorkStep
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public Map<String, Object> modify(SingleWorkStep singleWorkStep, Employee employee) throws Exception {
        Map<String, Object> map = isBlank(singleWorkStep);
        String modifierId = employee.getEmployeeId();
        if ((Boolean) map.get("state") == RespCodeEnum.RESP_CODE_ENUM_false.code()) return map;
        singleWorkStep.setModifierId(modifierId);
        singleWorkStep.setModifyTime(DateUtil.getTimeString());
        int num = stepMapper.updateByPrimaryKeySelective(singleWorkStep);
        map.put("state", num > 0 ? RespCodeEnum.RESP_CODE_ENUM_true.code() : RespCodeEnum.RESP_CODE_ENUM_false.code());
        map.put("msg", num > 0 ? BackMessage.MODIFY_OK : BackMessage.MODIFY_FAIL);
        return map;
    }

    /**
     * 将步骤上移
     *
     * @param stepId
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public Map<String, Object> upStep(String stepId) throws Exception {
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isBlank(stepId)) {
            map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());
            map.put("msg", "stepId不能为空！");
            return map;
        }
        //获取原步骤对象的索引号
        SingleWorkStep step1 = stepMapper.selectByPrimaryKey(stepId);
        int index1 = step1.getStepIndex();
        //判断是否能移动
        if (index1 <= 1) {
            map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());
            map.put("msg", "已经到最前面了，不能再移动了！");
            return map;
        }
        //获取上一级步骤对象
        SingleWorkStep step2 = getStepBA(stepId, "prev");
        int index2 = step2.getStepIndex();
        if (stepMapper.updateIndex(index2, step1.getStepId()) > 0 && stepMapper.updateIndex(index1, step2.getStepId()) > 0) {
            map.put("state", RespCodeEnum.RESP_CODE_ENUM_true.code());
            map.put("msg", BackMessage.MOVE_UP_OK);
        } else {
            map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());
            map.put("msg", BackMessage.MOVE_UP_FAIL);
        }
        return map;
    }

    /**
     * 将步骤下移
     *
     * @param stepId
     * @return
     */
    @Override
    public Map<String, Object> downStep(String stepId) throws Exception {
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isBlank(stepId)) {
            map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());
            map.put("msg", "stepId不能为空！");
            return map;
        }
        //获取原步骤对象
        SingleWorkStep step1 = stepMapper.selectByPrimaryKey(stepId);
        int num = stepMapper.selectCountByStep(new SingleWorkStep(step1.getWorkContentId()));
        int index1 = step1.getStepIndex();
        //判断是否能移动
        if (index1 >= num) {
            map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());
            map.put("msg", "已经到最后面了，不能再移动了！");
            return map;
        }
        //获取下一级步骤对象
        SingleWorkStep step2 = getStepBA(stepId, "after");
        int index2 = step1.getStepIndex();
        if (stepMapper.updateIndex(index1, step2.getStepId()) > 0 && stepMapper.updateIndex(index2, step1.getStepId()) > 0) {
            map.put("state", RespCodeEnum.RESP_CODE_ENUM_true.code());
            map.put("msg", BackMessage.MOVE_DOWN_OK);
        } else {
            map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());
            map.put("msg", BackMessage.MOVE_DOWN_FAIL);
        }
        return map;
    }

    /**
     * 导入需要的操作单元步骤
     *
     * @param stepIds
     * @param version
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public Map<String, Object> importUnitStep(List<String> stepIds, String workInstanceId, BigDecimal version, Employee employee) throws Exception {
        Map<String, Object> map = new HashMap<>();
        // Employee employee = employeeService.getLoginEmployee();
        String creatorId = employee.getEmployeeId();
        map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());
        if (stepIds == null || stepIds.size() == 0) {
            map.put("msg", "请选择步骤后再试！");
            return map;
        }
        if (StringUtils.isBlank(workInstanceId)) {
            map.put("msg", "请指定单项工作内容！");
            return map;
        }
        if (version == null) {
            version = new BigDecimal(1);
            stepMapper.updateStepVersion(new WorkCellInstance(workInstanceId, version));
        }
        int num = 0;

        for (String stepId : stepIds) {
            SingleWorkStep step = stepMapper.selectByPrimaryKey(stepId);
            int maxIndex = stepMapper.selectCountByStep(new SingleWorkStep(workInstanceId));
            step.setCreatorId(creatorId);
            step.setCreateTime(DateUtil.getTimeString());
            step.setCellId(null);
            step.setStepIndex(maxIndex + 1);
            step.setStepId(UniqueUtil.uuid());
            step.setWorkContentId(workInstanceId);
            step.setCreateTime(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS));
            step.setModifyTime(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS));
            step.setVersion(version);
            num += stepMapper.insertSelective(step);
            map = copyDataItem(stepId, step.getStepId(), employee);
            if ((Boolean) map.get("noItem")) {
                continue;
            }
        }
        map.put("state", num > 0 ? RespCodeEnum.RESP_CODE_ENUM_true.code() : RespCodeEnum.RESP_CODE_ENUM_false.code());
        map.put("msg", num > 0 ? BackMessage.IMPORT_OK : BackMessage.IMPORT_FAIL);
        return map;
    }

    /**
     * 克隆数据项
     *
     * @param oldStepId
     * @param newStepId
     * @return
     * @throws Exception
     */
    private Map<String, Object> copyDataItem(String oldStepId, String newStepId, Employee employee) throws Exception {
        //Employee employee = employeeService.getLoginEmployee();
        String creatorId = employee.getEmployeeId();
        Map<String, Object> map = new HashMap<>();
        List<SingleWorkStepDataItem> dataItems = getDataItemByStepId(oldStepId);
        if (dataItems == null || dataItems.size() == 0) {
            map.put("noItem", RespCodeEnum.RESP_CODE_ENUM_true.code());
            return map;
        }
        //遍历数据项
        for (SingleWorkStepDataItem dataItem : dataItems) {
            String newDataItemId = UniqueUtil.uuid();
            dataItem.setStepId(newStepId);
            dataItem.setDataItemId(newDataItemId);
            dataItem.setCreatorId(creatorId);
            dataItem.setCreatTime(DateUtil.getTimeString());
            dataItem.setModifyTime(null);
            if (dataItem.getRadios() != null) {
                dataItem.getRadios().setDataItemId(newDataItemId);
                dataItem.getRadios().setCreatorId(creatorId);
                dataItem.getRadios().setCreateTime(new Date());
                dataItem.getRadios().setModifyTime(null);
            }
            if (dataItem.getChecks() != null) {
                dataItem.getChecks().setDataItemId(newDataItemId);
                dataItem.getChecks().setCreatorId(creatorId);
                dataItem.getChecks().setCreateTime(new Date());
                dataItem.getChecks().setModifyTime(null);
            }
        }
        SingleWorkStepDataItem[] items = dataItems.toArray(new SingleWorkStepDataItem[dataItems.size()]);
        map = addDataItem(items, employee);
        return map;
    }

    /**
     * 新增步骤版本
     *
     * @param workContentId
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object> addStepVersion(String workContentId, Employee employee) throws Exception {
        String creatorId = employee.getEmployeeId();
        Map<String, Object> map = new HashMap<>();
        WorkCellInstance work = getWorkContent(workContentId);
        //获取工作内容现有的步骤列表
        if (work == null || work.getStepVersion() == null) {
            map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());
            map.put("msg", BackMessage.GET_NONE);
            return map;
        }
        List<SingleWorkStep> stepList = stepMapper.selectByWorkInstanceId(workContentId, work.getStepVersion());
        if (stepList == null || stepList.size() == 0) {
            map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());
            map.put("msg", BackMessage.GET_NONE);
            return map;
        }
        int num = 0;
        for (SingleWorkStep step : stepList) {
            String oldId = step.getStepId();
            step.setCreateTime(DateUtil.getTimeString());
            step.setStepId(UniqueUtil.uuid());
            step.setCreatorId(creatorId);
            step.setModifyTime(null);
            step.setVersion(work.getStepVersion().add(new BigDecimal(0.01)));
            map = copyDataItem(oldId, step.getStepId(), employee);
            num += stepMapper.insertSelective(step);
        }
        map.put("state", num > 0 ? RespCodeEnum.RESP_CODE_ENUM_true.code() : RespCodeEnum.RESP_CODE_ENUM_false.code());
        map.put("msg", num > 0 ? BackMessage.ADD_OK : BackMessage.ADD_FAIL);
        return map;
    }

    /**
     * 获取实体阈值，先获取实体绑定的设备的阈值，再获取实体的阈值
     *
     * @param deviceThreshold
     * @return
     * @throws Exception
     */
//    @Override
//    public Map<String, Object> getEntityThres(DeviceThreshold deviceThreshold) throws Exception {
//        Map<String, Object> map = new HashMap<>();
//        if (deviceThreshold.getEntityId() != null) {
//            Entity entity = entityMapper.selectByEnId(deviceThreshold.getEntityId());
//            if (!StringUtils.isBlank(entity.getDeviceId())) {
//                DeviceThreshold dt = new DeviceThreshold();
//                dt.setDeviceId(entity.getDeviceId());
//                dt.setEntityId(deviceThreshold.getEntityId());
//                dt.setOffset(deviceThreshold.getOffset());
//                dt.setLimit(deviceThreshold.getLimit());
//                map = deviceService.getDeviceThres(dt);
//            } else {
//                map = deviceService.getDeviceThres(deviceThreshold);
//            }
//        }
//        return map;
//    }

    /**
     * 删除单项步骤
     *
     * @param stepId
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public Map<String, Object> del(String stepId) throws Exception {
        Map<String, Object> map = new HashedMap();
        if (StringUtils.isBlank(stepId)) {
            map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());
            map.put("msg", "stepId不能为空！");
            return map;
        }
        //获取当前步骤后面的所有步骤对象list
        List<SingleWorkStep> stepList = getAfterSteps(stepId);
        //将后面的步骤往前提升一级
        if (stepList != null && stepList.size() > 0) {
            for (SingleWorkStep step : stepList) {
                step.setStepIndex(step.getStepIndex() - 1);
                stepMapper.updateByPrimaryKeySelective(step);
            }
        }
        if (stepMapper.updateStatus(stepId) > 0) {
            map.put("state", RespCodeEnum.RESP_CODE_ENUM_true.code());
            map.put("msg", BackMessage.DEL_OK);
            return map;
        }
        map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());
        map.put("msg", BackMessage.DEL_FAIL);
        return map;
    }

    /**
     * 批量删除单项步骤
     *
     * @param stepIds
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public Map<String, Object> delBatch(String[] stepIds, String workContentId) throws Exception {
        Map<String, Object> map = new HashedMap();
        if (stepIds == null || stepIds.length == 0) {
            map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());
            map.put("msg", BackMessage.EMPTY_PARAMETER);
            return map;
        }
        List<String> stepList = new ArrayList<>();
        for (int i = 0; i < stepIds.length; i++) {
            stepList.add(stepIds[i]);
        }
        if (stepMapper.updateStatusBatch(stepList) > 0) {
            //获取工作内容
            WorkCellInstance work = getWorkContent(workContentId);
            //定义查询条件
            SingleWorkStep step = new SingleWorkStep(workContentId);
            step.setVersion(work.getStepVersion());
            //查询删除后的步骤list
            List<SingleWorkStep> steplist = stepMapper.selectByStepSelect(step);
            //对删除后的步骤list重新排序
            resortStep(steplist);
            map.put("state", RespCodeEnum.RESP_CODE_ENUM_true.code());
            map.put("msg", BackMessage.DEL_OK);
            return map;
        }
        map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());
        map.put("msg", BackMessage.DEL_FAIL);
        return map;
    }

    /**
     * 按stepId获取单项步骤的详细信息
     *
     * @param stepId
     * @return
     * @throws Exception
     */
    @Override
    public SingleWorkStep getStepById(String stepId) throws Exception {
        return StringUtils.isBlank(stepId) ? null : stepMapper.selectByPrimaryKey(stepId);
    }

    /**
     * 获取单项工作步骤分页列表
     *
     * @param singleWorkStep
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object> search(SingleWorkStep singleWorkStep) throws Exception {
        return getStepByWorkId(singleWorkStep);
    }

    /**
     * 对工作内容的操作单元进行判断是否含有步骤，如果含有步骤则
     * 获取操作单元的步骤列表
     *
     * @param singleWorkStep
     * @return
     * @throws Exception
     */
    public Map<String, Object> getStepByCellId(SingleWorkStep singleWorkStep) throws Exception {
        Map<String, Object> map = new HashMap<>();
        if (!StringUtils.isBlank(singleWorkStep.getWorkContentId())) {
            //获取工作内容对象
            WorkCellInstance workCellInstance = getWorkContent(singleWorkStep.getWorkContentId());
            if (workCellInstance == null || StringUtils.isBlank(workCellInstance.getCellId())) return map;
            SingleWorkStep step = new SingleWorkStep();
            step.setCellId(workCellInstance.getCellId());
            step.setOffset(singleWorkStep.getOffset());
            //设置分页参数
            if (step.getOffset() == null) step.setOffset(0);
            step.setLimit(6);
            Integer total = stepMapper.selectCountByStep(step);
            //设置按操作单元进行查询
            if (total > 0) {
                List<SingleWorkStep> stepList = stepMapper.selectByStep(step);
                setParentName(stepList);
                map.put("total", total);
                map.put("rows", stepList);
            }
        }
        return map;
    }

    /**
     * 重新排序
     *
     * @param steplist
     */
    public boolean resortStep(List<SingleWorkStep> steplist) throws Exception {
        int index = 0;
        if (steplist != null && steplist.size() > 0) {
            int num = 0;
            for (SingleWorkStep step : steplist) {
                index++;
                step.setStepIndex(index);
                if (!StringUtils.isBlank(step.getCreateTime())) {
                    step.setCreateTime(step.getCreateTime().substring(0, step.getCreateTime().length() - 2));
                }
                if (!StringUtils.isBlank(step.getModifyTime())) {
                    step.setModifyTime(step.getModifyTime().substring(0, step.getModifyTime().length() - 2));
                }
                num += stepMapper.updateByPrimaryKeySelective(step);
            }
            if (num > 0) {
                return RespCodeEnum.RESP_CODE_ENUM_true.code();
            }
        }
        return RespCodeEnum.RESP_CODE_ENUM_false.code();
    }
    /*
    ---------------------以下是私有方法-------------------------------------------------------------------------------------------
     */

    /**
     * 获取当前工作内容的步骤数量，即最大Index索引号
     *
     * @param workContentId
     * @return
     */
    private Integer getCurrentNum(String workContentId, BigDecimal version) {
        SingleWorkStep step = new SingleWorkStep(workContentId);
        step.setVersion(version);
        return stepMapper.selectCountByStep(step);
    }

    /**
     * 获取上级或下级步骤对象
     * direction=“prev”当前步骤前的
     * direction=“after”当前步骤后的
     *
     * @param stepId
     * @return
     */
    private SingleWorkStep getStepBA(String stepId, String direction) throws Exception {
        SingleWorkStep step = stepMapper.selectByPrimaryKey(stepId);
        int index = step.getStepIndex();
        String workContentId = step.getWorkContentId();
        String cellId = step.getCellId();
        BigDecimal version = step.getVersion();
        int num = 0;
        if (cellId != null) {
            SingleWorkStep stept = new SingleWorkStep();
            stept.setCellId(cellId);
            num = stepMapper.selectCountByStep(stept);
        }
        if (workContentId != null) {
            SingleWorkStep stept = new SingleWorkStep();
            stept.setWorkContentId(workContentId);
            stept.setVersion(version);
            num = stepMapper.selectCountByStep(stept);
        }
        if ("prev".equals(direction)) {
            if (index <= 1) return null;
            if (cellId != null) {
                SingleWorkStep step1 = new SingleWorkStep();
                step1.setCellId(cellId);
                step1.setStepIndex(index - 1);
                step1.setVersion(version);
                return stepMapper.selectByStepSelect(step1).get(0);
            }
            if (workContentId != null) {
                SingleWorkStep step1 = new SingleWorkStep(index - 1, workContentId);
                step1.setVersion(version);
                return stepMapper.selectByStepSelect(step1).get(0);
            }
        } else {
            if (index >= num) return null;
            if (cellId != null) {
                SingleWorkStep step1 = new SingleWorkStep();
                step1.setCellId(cellId);
                step1.setStepIndex(index + 1);
                step1.setVersion(version);
                return stepMapper.selectByStepSelect(step1).get(0);
            }
            if (workContentId != null) {
                SingleWorkStep step1 = new SingleWorkStep(index + 1, workContentId);
                step1.setVersion(version);
                return stepMapper.selectByStepSelect(step1).get(0);
            }
        }
        return null;
    }

    /**
     * 获取当前步骤后面的所有步骤
     *
     * @param stepId
     * @return
     * @throws Exception
     */
    private List<SingleWorkStep> getAfterSteps(String stepId) throws Exception {
        SingleWorkStep step = stepMapper.selectByPrimaryKey(stepId);
        int index = step.getStepIndex();
        String workContentId = step.getWorkContentId();
        return stepMapper.selectByBigThanIndex(index, workContentId, step.getVersion());
    }

    /**
     * 一站一案：根据一站一案查询当前版本的操作步骤
     *
     * @param singleWorkStep
     * @return
     * @throws Exception
     */
    private Map<String, Object> getStepByWorkId(SingleWorkStep singleWorkStep) throws Exception {
        /**
         * 根据当前一站一案启用版本号 ：进行查询
         */
        try {
            WorkCellInstanceVo workCellInstance = workCellInstanceService.loadWorkCellInstanceView(singleWorkStep.getWorkContentId());
            if (workCellInstance != null) {
                singleWorkStep.setCellId(workCellInstance.getCellId());
                singleWorkStep.setVersion(workCellInstance.getStepVersion());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return getStepList(singleWorkStep);
    }

    /**
     * 为每个步骤设置上级步骤名称
     *
     * @param stepList
     * @return
     * @throws Exception
     */
    private void setParentName(List<SingleWorkStep> stepList) throws Exception {
        if (stepList != null && stepList.size() > 0) {
            for (int i = 0; i < stepList.size(); i++) {
                SingleWorkStep prevStep = null;
                if (i > 0) {
                    prevStep = stepList.get(i - 1);
                }
                stepList.get(i).setStepTypeName(getStepTypeName(stepList.get(i).getStepType()));
                stepList.get(i).setParentStepName(prevStep == null ? null : prevStep.getStepName());
            }
        }
    }

    /**
     * 获取步骤类别号对应的步骤名称
     *
     * @param stepTypeId
     * @return
     */
    private String getStepTypeName(Integer stepTypeId) {
        if (stepTypeId != null) {
            for (StepStage ss : StepStage.values()) {
                if (ss.getCode() == stepTypeId) {
                    return ss.getDesc();
                }
            }
        }
        return null;
    }

    /**
     * 按ID查询工作内容
     *
     * @param workInstanceId
     * @return
     * @throws Exception
     */
    public WorkCellInstance getWorkContent(String workInstanceId) throws Exception {
        return stepMapper.selectWorkInstanceById(workInstanceId);
    }


    /**
     * 对SingleWorkStep参数进行判空
     *
     * @param singleWorkStep
     * @return
     */
    private Map<String, Object> isBlank(SingleWorkStep singleWorkStep) {
        Map<String, Object> map = new HashedMap();
        map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());
        if (StringUtils.isBlank(singleWorkStep.getStepId())) {
            map.put("msg", "ID不能为空");
            return map;
        }
        if (StringUtils.isBlank(singleWorkStep.getStepName())) {
            map.put("msg", "步骤名不能为空");
            return map;
        }
        if (singleWorkStep.getStepName().length() > 100) {
            map.put("msg", "步骤名长度不能超过100");
            return map;
        }
        if (StringUtils.isBlank(singleWorkStep.getControlMeasures())) {
            map.put("msg", "控制措施不能为空！");
            return map;
        }
        if (StringUtils.isBlank(singleWorkStep.getPotentialRisk())) {
            map.put("msg", "潜在风险不能为空！");
            return map;
        }
        if (singleWorkStep.getVersion() == null) {
            map.put("msg", "版本号不能为空！");
            return map;
        }
        map.put("state", RespCodeEnum.RESP_CODE_ENUM_true.code());
        return map;
    }
    /*
    ------------以下是数据项配置方法-----------------------------------------------------------------------------------
     */

    /**
     * 获取数据项列表
     *
     * @param stepId
     * @return
     */
    public List<SingleWorkStepDataItem> getDataItemByStepId(String stepId) {
        List<SingleWorkStepDataItem> dataItemList = StringUtils.isBlank(stepId) ? null : stepDataItemMapper.selectByStepId(stepId);
        if (dataItemList == null || dataItemList.size() == 0) {
            return null;
        }
        for (SingleWorkStepDataItem dataItem : dataItemList) {
            int type = dataItem.getStepDataItemType();
            switch (type) {
                case 2:
                    if (!StringUtils.isBlank(dataItem.getRadioName())) {
                        String[] dataItemRadioName = dataItem.getRadioName().split(",");
                        if(dataItemRadioName != null && dataItemRadioName.length > 0){
                            List list = new ArrayList<>();
                            for(int arr = 0 ; arr < dataItemRadioName.length ; arr ++){
                                Map<String,String> RadioData = new LinkedHashMap<>();
                                RadioData.put("radioName",dataItemRadioName[arr]);
                                list.add(RadioData);
                            }
                            dataItem.setRadioNamesList(list);
                        }
                        dataItem.setRadioNames(dataItem.getRadioName().split(","));
                    }
                    continue;
                case 3:
                    if (!StringUtils.isBlank(dataItem.getCheckName())) {
                        String[] dataItemCheckName = dataItem.getCheckName().split(",");
                        if(dataItemCheckName != null && dataItemCheckName.length > 0){
                             List list = new ArrayList<>();
                             for(int arr = 0 ; arr < dataItemCheckName.length ; arr ++){
                                Map<String,String> checkData = new LinkedHashMap<>();
                                 checkData.put("checkName",dataItemCheckName[arr]);
                                list.add(checkData);
                             }
                            dataItem.setCheckNamesList(list);
                        }
                        dataItem.setCheckNames(dataItem.getCheckName().split(","));
                    }
                    continue;
            }
        }
        return dataItemList;
    }

    /**
     * 添加数据项
     *
     * @param singleWorkStepDataItem
     * @return
     * @throws Exception
     */
    //@Transactional(propagation = Propagation.REQUIRED)
    public Map<String, Object> addDataItem(SingleWorkStepDataItem[] singleWorkStepDataItem, Employee employee) throws Exception {
        //设置创建人ID
        //Employee employee = employeeService.getLoginEmployee();
        String creatorId = employee.getEmployeeId();
        Map<String, Object> map = new HashMap<>();
        //对数据项参数进行校验
        for (int i = 0; i < singleWorkStepDataItem.length; i++) {
            Map<String, Object> obj = isBlank(singleWorkStepDataItem[i]);
            if ((Boolean) obj.get("state") == RespCodeEnum.RESP_CODE_ENUM_false.code()) {
                System.out.print("参数验证过程：：：：：" + obj.get("msg"));
                return map;
            }
        }
        map = addForEach(singleWorkStepDataItem, creatorId);
        if ((Boolean) map.get("state") == false) {
            return map;
        }
        map.put("msg", (Integer) map.get("num") > 0 ? BackMessage.ADD_OK : BackMessage.ADD_FAIL);
        return map;
    }

    /**
     * 遍历数据项数组，装配相关信息，并插入到数据库中
     *
     * @param singleWorkStepDataItem
     * @param createrId
     * @return
     * @throws Exception
     */
    private Map<String, Object> addForEach(SingleWorkStepDataItem[] singleWorkStepDataItem, String createrId) throws Exception {
        Map<String, Object> map = new HashMap<>();
        //对数据项数组进行循环
        int num = 0;
        String time = DateUtil.getTimeString();
        for (int i = 0; i < singleWorkStepDataItem.length; i++) {
            String dataItemId = UniqueUtil.uuid();
            singleWorkStepDataItem[i].setCreatorId(createrId);
            singleWorkStepDataItem[i].setCreatTime(time);
            map = addDataItem(singleWorkStepDataItem[i]);
            if ((Boolean) map.get("state") == RespCodeEnum.RESP_CODE_ENUM_false.code()) {
                //手动回滚事务
                //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return map;
            }
            num++;
        }
        map.put("state", RespCodeEnum.RESP_CODE_ENUM_true.code());
        map.put("num", num);
        return map;
    }

    /**
     * 单个添加数据项(无校验)
     *
     * @param dataItem
     * @return
     * @throws Exception
     */
    @Override
    //@Transactional(propagation = Propagation.REQUIRED)
    public Map<String, Object> addDataItem(SingleWorkStepDataItem dataItem) throws Exception {
        dataItem.setStatus(BigDecimal.valueOf(0));
        if(StringUtils.isNotEmpty(dataItem.getItemId())){
            dataItem.setItemType(BigDecimal.valueOf(0));
            ReportItem reportItem = reportItemMapper.selectByPrimaryKey(dataItem.getItemId()) ;
            // 判断长度
            if(reportItem.getColLength() != null){
                dataItem.setItemDataLength(reportItem.getColLength());
            }
            // 判断get字段长度
            if(reportItem.getColType() != null){
                dataItem.setItemDataType(reportItem.getColType());
            }
        }else{
            dataItem.setItemType(BigDecimal.valueOf(1));
        }

        Map<String, Object> map = new HashMap<>();
        int num = 0;
        //判断数据项类型
        switch (dataItem.getStepDataItemType()) {
            case 1:
                num += stepDataItemMapper.insertSelective(dataItem);
                break;
            case 2:
                map = addRadios(dataItem);
                if ((Boolean) map.get("state") == RespCodeEnum.RESP_CODE_ENUM_false.code()) return map;
                num += stepDataItemMapper.insertSelective(dataItem);
                break;
            case 3:
                map = addChecks(dataItem);
                if ((Boolean) map.get("state") == RespCodeEnum.RESP_CODE_ENUM_false.code()) {
                    //手动回滚事务
                    //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return map;
                }
                num += stepDataItemMapper.insertSelective(dataItem);
                break;
            case 4:
                num += stepDataItemMapper.insertSelective(dataItem);
                break;
            case 5:
                num += stepDataItemMapper.insertSelective(dataItem);
                break;
        }
        map.put("state", num > 0 ? RespCodeEnum.RESP_CODE_ENUM_true.code() : RespCodeEnum.RESP_CODE_ENUM_false.code());
        return map;
    }

    /**
     * @param item
     * @return
     * @throws Exception
     */
    @Override
    public Integer saveDataItem(SingleWorkStepDataItem item) throws Exception {
        int successNum = 0;
        //判断数据项类型
        switch (item.getStepDataItemType()) {
            case 1:
                successNum += stepDataItemMapper.insertSelective(item);
                break;
            case 2:
                 addRadios(item);
                successNum += stepDataItemMapper.insertSelective(item);
                break;
            case 3:
                 addChecks(item);
                successNum += stepDataItemMapper.insertSelective(item);
                break;
            case 4:
                successNum += stepDataItemMapper.insertSelective(item);
                break;
            case 5:
                successNum += stepDataItemMapper.insertSelective(item);
                break;
        }
        return successNum ;
    }


    /**
     * 添加多选框
     *
     * @param dataItem
     * @return
     */
    private Map<String, Object> addChecks(SingleWorkStepDataItem dataItem) {
        Map<String, Object> map = new HashMap<>();
        CheckboxType checks = new CheckboxType();
        List checkList =  dataItem.getCheckNamesList() ;
        String checkName = "";
        if(checkList!=null && checkList.size()>0){
            int checkInt = 0 ;
            for(Object check : checkList){
                if(checkInt == checkList.size() - 1){
                    checkName = checkName + check.toString();
                }else{
                    checkName = checkName + check.toString() +"," ;
                }
                checkInt ++ ;
            }
        }
        checks.setCheckboxTypeName(checkName);
        checks.setCheckboxTypeId(UniqueUtil.uuid());
        checks.setCreatorId(dataItem.getCreatorId());
        checks.setCreateTime(new Date());
        checks.setModifierId(dataItem.getCreatorId());
        checks.setModifyTime(new Date());
        checks.setDataItemId(dataItem.getDataItemId());
        //对多选框参数进行校验
        map = isBlank(checks);
        if ((Boolean) map.get("state") == RespCodeEnum.RESP_CODE_ENUM_false.code()) return map;
        int num = stepDataItemMapper.insertChecks(checks);
        map.put("state", num > 0 ? RespCodeEnum.RESP_CODE_ENUM_true.code() : RespCodeEnum.RESP_CODE_ENUM_false.code());
        map.put("msg", num > 0 ? "" : "添加多选框失败！");
        return map;
    }

    /**
     * 添加单选框
     *
     * @param dataItem
     * @return
     */
    private Map<String, Object> addRadios(SingleWorkStepDataItem dataItem) {
        Map<String, Object> map = new HashMap<>();
        RadioType radios = new RadioType();
        List radioList = dataItem.getRadioNamesList();
        String radioName = "" ;
        if(radioList!=null){
            int radioInt = 0 ;
            for(Object radio : radioList){
                if(radioInt == radioList.size() - 1){
                    radioName = radioName + radio.toString();
                }else{
                    radioName = radioName + radio.toString() +"," ;
                }
                radioInt ++ ;
            }
        }
        radios.setRadioTypeName(radioName);
        radios.setRadioTypeId(UniqueUtil.uuid());
        radios.setCreatorId(dataItem.getCreatorId());
        radios.setCreateTime(new Date());
        radios.setDataItemId(dataItem.getDataItemId());
        radios.setModifierId(dataItem.getCreatorId());
        radios.setModifyTime(new Date());
        //对单项框对象参数进行校验
        map = isBlank(radios);
        if ((Boolean) map.get("state") == RespCodeEnum.RESP_CODE_ENUM_false.code()) return map;
        int num = stepDataItemMapper.insertRadios(radios);
        map.put("state", num > 0 ? RespCodeEnum.RESP_CODE_ENUM_true.code() : RespCodeEnum.RESP_CODE_ENUM_false.code());
        map.put("msg", num > 0 ? "" : "添加多选框失败！");
        return map;
    }

    /**
     * 修改数据项
     *
     * @param singleWorkStepDataItem
     * @return
     * @throws Exception
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public Map<String, Object> modifyDataItem(SingleWorkStepDataItem singleWorkStepDataItem, Employee employee) throws Exception {
        //设置创建人ID
        String modifierId = employee.getEmployeeId();
        Map<String, Object> map = new HashMap<>();
        //对数据项参数进行校验
        if ((Boolean) isBlank(singleWorkStepDataItem).get("state") == RespCodeEnum.RESP_CODE_ENUM_false.code())
            return map;
        //设置修改人ID及修改时间
        singleWorkStepDataItem.setModifierId(modifierId);
        singleWorkStepDataItem.setModifyTime(DateUtil.getTimeString());
        //修改数据项
        map = modifyDataItemExpValidate(singleWorkStepDataItem);
        if (map.get("state") != null && (Boolean) map.get("state") == RespCodeEnum.RESP_CODE_ENUM_false.code()) {
            //手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return map;
        }
        return map;
    }

    /**
     * 修改数据项（无校验）
     *
     * @param dataItem
     * @return
     */
    public Map<String, Object> modifyDataItemExpValidate(SingleWorkStepDataItem dataItem) throws Exception {
        Map<String, Object> map = new HashMap<>();
        int num = 0;
        switch (dataItem.getStepDataItemType()) {
            case 1:
                break;
            case 2:
                map = modifyRadios(dataItem);
                break;
            case 3:
                map = modifyChecks(dataItem);
                break;
        }
        if (map.get("state") != null && (Boolean) map.get("state") == RespCodeEnum.RESP_CODE_ENUM_false.code())
            return map;
        num += stepDataItemMapper.updateByPrimaryKeySelective(dataItem);
        map.put("state", num > 0 ? RespCodeEnum.RESP_CODE_ENUM_true.code() : RespCodeEnum.RESP_CODE_ENUM_false.code());
        map.put("msg", num > 0 ? BackMessage.MODIFY_OK : BackMessage.MODIFY_FAIL);
        return map;
    }

    /**
     * 修改多选框
     *
     * @param dataItem
     * @return
     */
    private Map<String, Object> modifyChecks(SingleWorkStepDataItem dataItem) {
        Map<String, Object> map = new HashMap<>();
        CheckboxType checks = new CheckboxType();
        checks.setCheckboxTypeId(dataItem.getCheckboxId());
        checks.setCheckboxTypeName(dataItem.getCheckName());
        checks.setModifierId(dataItem.getModifierId());
        checks.setModifyTime(new Date());
        map = isBlank(checks);
        if ((Boolean) map.get("state") == RespCodeEnum.RESP_CODE_ENUM_false.code()) return map;
        int num = stepDataItemMapper.updateCheckSelect(checks);
        map.put("state", num > 0 ? RespCodeEnum.RESP_CODE_ENUM_true.code() : RespCodeEnum.RESP_CODE_ENUM_false.code());
        map.put("msg", num > 0 ? "" : "修改多选框失败！");
        return map;
    }

    /**
     * 修改单选框
     *
     * @param dataItem
     * @return
     */
    private Map<String, Object> modifyRadios(SingleWorkStepDataItem dataItem) {
        Map<String, Object> map = new HashMap<>();
        RadioType radios = new RadioType();
        radios.setRadioTypeId(dataItem.getRadioId());
        radios.setRadioTypeName(dataItem.getRadioName());
        radios.setModifierId(dataItem.getModifierId());
        radios.setModifyTime(new Date());
        map = isBlank(radios);
        if ((Boolean) map.get("state") == RespCodeEnum.RESP_CODE_ENUM_false.code()) return map;
        int num = stepDataItemMapper.updateRadioSelect(radios);
        map.put("state", num > 0 ? RespCodeEnum.RESP_CODE_ENUM_true.code() : RespCodeEnum.RESP_CODE_ENUM_false.code());
        map.put("msg", num > 0 ? "" : "修改单选框失败！");
        return map;
    }

    /**
     * 对radio参数进行校验
     *
     * @param radios
     * @return
     */
    private Map<String, Object> isBlank(RadioType radios) {
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isBlank(radios.getRadioTypeName())) {
            map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());
            map.put("msg", "单选框名称不能为空！");
            return map;
        }
        if (radios.getRadioTypeName().length() > 32) {
            map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());
            map.put("msg", "单选框名称长度为32字符以内！");
            return map;
        }
        if (StringUtils.isBlank(radios.getRadioTypeId())) {
            map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());
            map.put("msg", "单选框ID不能为空！");
            return map;
        }
        map.put("state", RespCodeEnum.RESP_CODE_ENUM_true.code());
        return map;
    }

    /**
     * 对check参数进行校验
     *
     * @param checks
     * @return
     */
    private Map<String, Object> isBlank(CheckboxType checks) {
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isBlank(checks.getCheckboxTypeName())) {
            map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());
            map.put("msg", "多选框名称不能为空！");
            return map;
        }
        if (checks.getCheckboxTypeName().length() > 32) {
            map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());
            map.put("msg", "多选框名称长度为32字符以内！");
            return map;
        }
        if (StringUtils.isBlank(checks.getCheckboxTypeId())) {
            map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());
            map.put("msg", "多选框ID不能为空！");
            return map;
        }
        map.put("state", RespCodeEnum.RESP_CODE_ENUM_true.code());
        return map;
    }

    /**
     * 按ID删除数据项
     *
     * @param dataItemId
     * @return
     * @throws Exception
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public Map<String, Object> delDataItem(String dataItemId) throws Exception {
        Map<String, Object> map = new HashMap();
        int num = StringUtils.isBlank(dataItemId) ? 0 : stepDataItemMapper.updateStatusById(dataItemId);
        map.put("msg", num > 0 ? BackMessage.DEL_OK : BackMessage.DEL_FAIL);
        return map;
    }

    /**
     * 对SingleWorkStepDataItem参数进行校验
     *
     * @param singleWorkStepDataItem
     * @return
     */
    public Map<String, Object> isBlank(SingleWorkStepDataItem singleWorkStepDataItem) {
        Map<String, Object> map = new HashedMap();
        map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());
        if (StringUtils.isBlank(singleWorkStepDataItem.getStepDataItemName())) {
            map.put("msg", "数据项名不能为空");
            return map;
        }
        if (singleWorkStepDataItem.getStepDataItemName().length() > 100) {
            map.put("msg", "数据项名长度为100字符以内");
            return map;
        }
        if (StringUtils.isBlank(singleWorkStepDataItem.getStepDataItemType().toString())) {
            map.put("msg", "数据项类型不能为空！");
            return map;
        }
        if (singleWorkStepDataItem.getStepDataItemType() < 1 && singleWorkStepDataItem.getStepDataItemType() > 4) {
            map.put("msg", "数据项类型只能是1-4的数字");
            return map;
        }
        if (StringUtils.isBlank(singleWorkStepDataItem.getDataItemId())) {
            map.put("msg", "数据项ID不能为空！");
            return map;
        }
        map.put("state", RespCodeEnum.RESP_CODE_ENUM_true.code());
        return map;
    }

    /**
     * 获取未应用的新版本步骤列表
     *
     * @param step
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object> getNewVersionStepListByWork(SingleWorkStep step) throws Exception {
        if (step.getWorkContentId() != null) {
            step.setVersion(getWorkContent(step.getWorkContentId()).getStepVersion().add(new BigDecimal(0.01)));
        }
        return getStepList(step);
    }

    /**
     * 应用新版本步骤
     *
     * @param work
     * @return
     */
    @Override
    public Map<String, Object> applyNewVersion(WorkCellInstance work) {
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isBlank(work.getWorkInstanceId()) && work.getStepVersion() == null) {
            map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());
            map.put("msg", BackMessage.EMPTY_PARAMETER);
            return map;
        }
        int num = stepMapper.updateStepVersion(work);
        map.put("state", num > 0 ? RespCodeEnum.RESP_CODE_ENUM_true.code() : RespCodeEnum.RESP_CODE_ENUM_false.code());
        map.put("msg", num > 0 ? BackMessage.APPLY_OK : BackMessage.APPLY_FAIL);
        return map;
    }

    /**
     * 公共查询步骤方法
     *
     * @param step
     * @return
     * @throws Exception
     */
    private Map<String, Object> getStepList(SingleWorkStep step) throws Exception {
        Map<String, Object> map = new HashMap<>();
        List<SingleWorkStep> stepList = stepMapper.selectByStep(step);
        Integer total = getStepNum(step);
        if (total > 0) setParentName(stepList);
        if (stepList != null && stepList.size() > 0) {
            map.put("total", total);
            map.put("rows", stepList);
        }
        return map;
    }

    /**
     * 查询步骤数量
     *
     * @param step
     * @return
     */
    public int getStepNum(SingleWorkStep step) throws Exception {
        return stepMapper.selectCountByStep(step);
    }

    /**
     * 得到操作单元的操作步骤
     *
     * @param workConetId
     * @return
     */
    @Override
    public List<SingleWorkStep> getStepByWorkContentId(String workConetId, String stepVersion, String isStatus) {
        try {
            SingleWorkStep singleWorkStep = new SingleWorkStep();
            if ("details".equals(isStatus)) {
                singleWorkStep.setVersion(new BigDecimal(stepVersion));
                singleWorkStep.setWorkContentId(workConetId);
                return stepMapper.selectByStep(singleWorkStep);
            } else {
                Version version = versionService.queryMaxVersion(workConetId);
                List<SingleWorkStep> list = stepMapper.queryContentVersion(workConetId);
                if (list != null && list.size() > 0) {
                    singleWorkStep.setVersion(null);
                } else {
                    if (version != null && version.getVersionNumber() != null) {
                        singleWorkStep.setVersion(version.getVersionNumber().setScale(2, BigDecimal.ROUND_HALF_UP));
                    }
                }
                singleWorkStep.setWorkContentId(workConetId);
                return stepMapper.selectByStep(singleWorkStep);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 添加步骤(操作单元)
     *
     * @param singleWorkSteps
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void addStep(List<SingleWorkStep> singleWorkSteps, String workConetId, Employee employee) throws Exception {
        // Employee employee = employeeService.getLoginEmployee();
        String creatorId = employee.getEmployeeId();
       /* for(SingleWorkStep singleWorkStep:singleWorkSteps){
            if(singleWorkStep.getStepId()==null){
                singleWorkStep.setStepId(UniqueUtil.uuid());
                singleWorkStep.setCreatorId(creatorId);
                singleWorkStep.setCreateTime(DateUtil.getTimeString());
                singleWorkStep.setModifierId(creatorId);
                singleWorkStep.setModifyTime(DateUtil.getTimeString());
                singleWorkStep.setStatus(0);
                stepMapper.insertSelective(singleWorkStep);
            }else{
                singleWorkStep.setModifierId(creatorId);
                singleWorkStep.setModifyTime(DateUtil.getTimeString());
                stepMapper.updateByPrimaryKeySelective(singleWorkStep);
            }
        }*/
        List<SingleWorkStep> list = stepMapper.queryContentVersion(workConetId);
        if (list != null && list.size() > 0) {
            for (SingleWorkStep singleWorkStep : singleWorkSteps) {
                if (singleWorkStep.getStepId() == null) {
                    singleWorkStep.setStepId(UniqueUtil.uuid());
                    singleWorkStep.setCreatorId(creatorId);
                    singleWorkStep.setCreateTime(DateUtil.getTimeString());
                    singleWorkStep.setModifierId(creatorId);
                    singleWorkStep.setModifyTime(DateUtil.getTimeString());
                    singleWorkStep.setStatus(0);
                    //保存上传图像
                    fileService.addFile(singleWorkStep.getUploadFiles(), singleWorkStep.getDeletedFiles(), singleWorkStep.getStepId());
                    if (singleWorkStep.getUploadFiles() != null && singleWorkStep.getUploadFiles().length() > 0) {
                        singleWorkStep.setHasPic(1);
                    }
                    stepMapper.insertSelective(singleWorkStep);
                } else {
                    //保存上传图像
                    fileService.addFile(singleWorkStep.getUploadFiles(), singleWorkStep.getDeletedFiles(), singleWorkStep.getStepId());
                    if (singleWorkStep.getUploadFiles() != null && singleWorkStep.getUploadFiles().length() > 0) {
                        singleWorkStep.setHasPic(1);
                    }
                    singleWorkStep.setModifierId(creatorId);
                    singleWorkStep.setModifyTime(DateUtil.getTimeString());
                    stepMapper.updateByPrimaryKeySelective(singleWorkStep);
                }
            }
        } else {
            for (SingleWorkStep singleWorkStep : singleWorkSteps) {
                singleWorkStep.setStepId(UniqueUtil.uuid());
                singleWorkStep.setCreatorId(creatorId);
                singleWorkStep.setCreateTime(DateUtil.getTimeString());
                singleWorkStep.setModifierId(creatorId);
                //保存上传图像
                fileService.addFile(singleWorkStep.getUploadFiles(), singleWorkStep.getDeletedFiles(), singleWorkStep.getStepId());
                if (singleWorkStep.getUploadFiles() != null && singleWorkStep.getUploadFiles().length() > 0) {
                    singleWorkStep.setHasPic(1);
                }
                singleWorkStep.setModifyTime(DateUtil.getTimeString());
                singleWorkStep.setStatus(0);
                singleWorkStep.setVersion(null);
                stepMapper.insertSelective(singleWorkStep);
            }
        }
    }

    /**
     * 根据操作单元删除步骤
     *
     * @param workContentId
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public Integer delStepByContentId(String workContentId) throws Exception {
        // return  stepMapper.delStepByWorkContentId(workContentId);
        return 0;
    }

    /**
     * @param singleWorkStep 步骤基本信息
     * @param employee 操作人员基本信息
     */
    @Override
    public void batchAddDataItem(SingleWorkStep singleWorkStep, Employee employee) {
        // 新版一站一案数据项保存
        String dataItemJsonStr = singleWorkStep.getDataItem();
        if(StringUtils.isNotEmpty(dataItemJsonStr)){
            JSONObject dataItemObj = JSON.parseObject(dataItemJsonStr);
            // 本地数据项
            JSONArray thisDataItem = dataItemObj.getJSONArray("thisDataItem");
            // 接入第三方数据项
            JSONArray otherDataItem = dataItemObj.getJSONArray("otherDataItem");
            if(thisDataItem != null && thisDataItem.size() > 0){
               for(int thisData = 0 ; thisData < thisDataItem.size() ;  thisData ++ ){
                    JSONObject jsonObject =  thisDataItem.getJSONObject(thisData);
                    SingleWorkStepDataItem stepDataItem = offsetDataItem(jsonObject);
                   // 由于数据项需要插入到其他表中需要发送给第三方，所以现在的数据必须为16位数限制
                    stepDataItem.setDataItemId(UniqueUtil.uuid16());
                    stepDataItem.setStepId(singleWorkStep.getStepId());
                    stepDataItem.setCreatorId(employee.getEmployeeId());
                    stepDataItem.setModifierId(employee.getEmployeeId());
                    stepDataItem.setCreatTime(DateUtil.DateToString(new Date(),DateStyle.YYYY_MM_DD_HH_MM));
                    stepDataItem.setModifyTime(DateUtil.DateToString(new Date(),DateStyle.YYYY_MM_DD_HH_MM));
                    stepDataItem.setStatus(new BigDecimal(0));
                    stepDataItem.setItemType(new BigDecimal(1));
                   try {
                       this.saveDataItem(stepDataItem);
                   } catch (Exception e) {
                       e.printStackTrace();
                   }
                   // 进行数据问题处理
               }
            }
            // 接入其他数据项
            if(otherDataItem != null && otherDataItem.size() > 0){
                for(int otherData = 0 ; otherData < otherDataItem.size() ;  otherData ++ ){
                    JSONObject otherObject =  otherDataItem.getJSONObject(otherData);
                    List<SingleWorkStepDataItem> stepDataItems = offsetDataItemList(otherObject);
                    // 进行数据问题处理
                    if(stepDataItems != null && stepDataItems.size() > 0){
                            for(SingleWorkStepDataItem stepDataItem:stepDataItems){
                                    stepDataItem.setDataItemId(UniqueUtil.uuid16());
                                    stepDataItem.setStepId(singleWorkStep.getStepId());
                                    stepDataItem.setCreatorId(employee.getEmployeeId());
                                    stepDataItem.setModifierId(employee.getEmployeeId());
                                    stepDataItem.setCreatTime(DateUtil.DateToString(new Date(),DateStyle.YYYY_MM_DD_HH_MM));
                                    stepDataItem.setModifyTime(DateUtil.DateToString(new Date(),DateStyle.YYYY_MM_DD_HH_MM));
                                    stepDataItem.setStatus(new BigDecimal(0));
                                    stepDataItem.setItemType(new BigDecimal(0));
                                    stepDataItem.setItemDataType("VARCHAR2(32)"); // 平板需要，用于兼容以前版本
                                    try {
                                        this.saveDataItem(stepDataItem);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                            }
                    }
                }
            }
        }else{
            logger.info(":SingleWorkStep-->该步骤数据项"+JSON.toJSONString(singleWorkStep));
        }
    }

    /**
     * @param jsonObject 将前端传回的数据格式进行转换成 数据项实体类
     * @return
     */
    public SingleWorkStepDataItem offsetDataItem(JSONObject jsonObject){
        SingleWorkStepDataItem  dataItem =  new SingleWorkStepDataItem();
        Object  devicePropertyId =  jsonObject.get("devicePropertyId") ;
        if(!org.springframework.util.StringUtils.isEmpty(devicePropertyId)){
            dataItem.setDevicePropertyId(devicePropertyId.toString());
        }
        // 数据项名称
        Object  stepDataItemName =  jsonObject.get("stepDataItemName") ;
        if(!org.springframework.util.StringUtils.isEmpty(stepDataItemName)){
            dataItem.setStepDataItemName(stepDataItemName.toString());
        }
        //
        Object  stepDataItemType =  jsonObject.get("stepDataItemType") ;
        if(!org.springframework.util.StringUtils.isEmpty(stepDataItemType)){
            dataItem.setStepDataItemType(Short.valueOf(stepDataItemType.toString()));
        }
        // 多个选项 进行转换
        JSONArray checkNamesList = jsonObject.getJSONArray("checkNamesList");
        if(checkNamesList != null && checkNamesList.size() > 0){
            String[] checkNames = new String[checkNamesList.size()];
            List checkList = new ArrayList<>();
                //切换东西 和 消除东西
            for(int checkArr = 0 ; checkArr < checkNamesList.size() ; checkArr++ ){
                     JSONObject object = checkNamesList.getJSONObject(checkArr);
                     if(object != null){
                         checkList.add(object.get("checkName"));
                         checkNames[checkArr] = object.get("checkName").toString();
                     }
            }
            dataItem.setCheckNamesList(checkList);
            dataItem.setCheckNames(checkNames);
        }
        // 单选项进行转换
        JSONArray radioNamesList = jsonObject.getJSONArray("radioNamesList");
        if(radioNamesList != null && radioNamesList.size() > 0){
            String[] radioNames = new String[radioNamesList.size()];
            List radioList = new ArrayList<>();
            for(int radioArr = 0 ; radioArr < radioNamesList.size() ; radioArr++ ){
                JSONObject object = radioNamesList.getJSONObject(radioArr);
                if(object != null){
                    radioList.add(object.get("radioName"));
                    radioNames[radioArr] = object.get("radioName").toString();
                }
            }
            dataItem.setRadioNames(radioNames);
            dataItem.setRadioNamesList(radioList);
        }
        // 单位
        Object  stepDataItemUnit =  jsonObject.get("stepDataItemUnit") ;
        if(!org.springframework.util.StringUtils.isEmpty(stepDataItemUnit)){
            dataItem.setStepDataItemUnit(stepDataItemUnit.toString());
        }
        // 最大值
        Object  maxVal =  jsonObject.get("maxVal") ;
        if(!org.springframework.util.StringUtils.isEmpty(maxVal)){
            dataItem.setMaxVal(new BigDecimal(maxVal.toString()));
        }
        // 最小值
        Object  minVal =  jsonObject.get("minVal") ;
        if(!org.springframework.util.StringUtils.isEmpty(minVal)){
            dataItem.setMinVal(new BigDecimal(minVal.toString()));
        }
        Object  itemId =  jsonObject.get("itemId") ;
        if(!org.springframework.util.StringUtils.isEmpty(itemId)){
            dataItem.setItemId(itemId.toString());
        }

        Object  dataItemName =  jsonObject.get("dataItemName") ;
        if(!org.springframework.util.StringUtils.isEmpty(dataItemName)){
            dataItem.setStepDataItemName(dataItemName.toString());
        }

        Object dataTimeType =  jsonObject.get("dataTimeType") ;
        if(!org.springframework.util.StringUtils.isEmpty(dataTimeType)){
            dataItem.setDataTimeType(dataTimeType.toString());
        }
        return dataItem  ;
    }

    /**
     * 将集成手工录入平台中的数据项进行转换
     * @param jsonObject 将前端传回的数据格式进行转换成 数据项实体类
     * @return
     */
    public List<SingleWorkStepDataItem> offsetDataItemList(JSONObject jsonObject){
        List<SingleWorkStepDataItem> stepDataItems = new ArrayList<>();
        Object orgId = jsonObject.get("orgId");
        Object orgName = jsonObject.get("orgName");
        Object reportId = jsonObject.get("reportId");
        Object reportName = jsonObject.get("reportName");
        Object dataItemPattern = jsonObject.get("dataItemPattern");
        if(!org.springframework.util.StringUtils.isEmpty(orgId) &&
                !org.springframework.util.StringUtils.isEmpty(orgName) &&
                !org.springframework.util.StringUtils.isEmpty(reportId) &&
                !org.springframework.util.StringUtils.isEmpty(reportName) &&
                !org.springframework.util.StringUtils.isEmpty(dataItemPattern)){
            JSONArray jsonArray =  jsonObject.getJSONArray("dataItemArray");
            if(jsonArray != null && jsonArray.size() > 0){
                for(int arr = 0 ; arr < jsonArray.size() ; arr++){
                    SingleWorkStepDataItem stepDataItem = offsetDataItem(jsonArray.getJSONObject(arr));

                    stepDataItem.setOrgId(orgId.toString());
                    stepDataItem.setOrgName(orgName.toString());
                    stepDataItem.setReportId(reportId.toString());
                    stepDataItem.setReportName(reportName.toString());
                    stepDataItem.setDataItemPattern(dataItemPattern.toString());
                    Object groupId = jsonObject.get("groupId") ;
                    if(!org.springframework.util.StringUtils.isEmpty(groupId)){
                        stepDataItem.setGroupId(groupId.toString());
                    }
                    stepDataItems.add(stepDataItem);
                }
            }
        }
        return stepDataItems ;
    }


    @Override
    public List<SingleWorkStepDataItem> offsetList(List<SingleWorkStepDataItem> singleWorkStepDataItemList) {
        List<SingleWorkStepDataItem> returnList = new ArrayList<>();
        Map<String,List<SingleWorkStepDataItem>> stringListMap = new LinkedHashMap<>();
        if(singleWorkStepDataItemList != null && singleWorkStepDataItemList.size() > 0){
            // 接入数据项
            for(SingleWorkStepDataItem stepDataItem : singleWorkStepDataItemList){
                List<SingleWorkStepDataItem> stepDataItems = stringListMap.get(stepDataItem.getGroupId());
                if(stepDataItem.getItemType().floatValue() == 0){
                    if(stepDataItems ==null ){
                        stepDataItems = new ArrayList<>();
                    }
                    stepDataItems.add(stepDataItem);
                    stringListMap.put(stepDataItem.getGroupId(),stepDataItems);
                }
            }
        }
        //
        if(stringListMap != null && stringListMap.size() > 0){
            for (Map.Entry<String, List<SingleWorkStepDataItem>> stringListEntry : stringListMap.entrySet()) {
                SingleWorkStepDataItem stepDataItem = new SingleWorkStepDataItem();      //
                List<SingleWorkStepDataItem> newStepDataItemList = new ArrayList<>();    // 子项
                List<SingleWorkStepDataItem> groupSameList = stringListEntry.getValue(); // 相同项
                String itemIds = "" ;
                String itemNames = "" ;
                int itemInt = 0  ;
                // 循环组装
                for(SingleWorkStepDataItem singleWorkStepDataItem:groupSameList){
                    stepDataItem.setItemDataType(singleWorkStepDataItem.getItemDataType());
                    stepDataItem.setReportName(singleWorkStepDataItem.getReportName());
                    stepDataItem.setReportId(singleWorkStepDataItem.getReportId());
                    stepDataItem.setItemId(singleWorkStepDataItem.getItemId());
                    stepDataItem.setStepDataItemName(singleWorkStepDataItem.getStepDataItemName());
                    stepDataItem.setOrgId(singleWorkStepDataItem.getOrgId());
                    stepDataItem.setOrgName(singleWorkStepDataItem.getOrgName());
                    stepDataItem.setDataItemPattern(singleWorkStepDataItem.getDataItemPattern());
                    stepDataItem.setStepDataItemName(singleWorkStepDataItem.getStepDataItemName());
                    stepDataItem.setDataItemName(singleWorkStepDataItem.getStepDataItemName());
                    singleWorkStepDataItem.setDataItemName(singleWorkStepDataItem.getStepDataItemName());
                    newStepDataItemList.add(singleWorkStepDataItem);
                    if(itemInt == groupSameList.size() - 1){
                        itemIds = itemIds + singleWorkStepDataItem.getItemId();
                        itemNames = itemNames + singleWorkStepDataItem.getStepDataItemName();
                    }else{
                        itemIds = itemIds + singleWorkStepDataItem.getItemId()+",";
                        itemNames = itemNames + singleWorkStepDataItem.getStepDataItemName()+",";
                    }
                    itemInt ++ ;
                }
                stepDataItem.setItemNames(itemNames);
                stepDataItem.setItemIds(itemIds);
                stepDataItem.setDataItemArray(newStepDataItemList);
                returnList.add(stepDataItem);
            }
        }

        return returnList ;
    }


    /**
     * @param   dataItemId 根据步骤数据项Id 查询基本信息
     */
    @Override
    public SingleWorkStepDataItem getSingleWorkStepDataItemByDataItemId(String dataItemId) {
        return stepDataItemMapper.selectByPrimaryKey(dataItemId);
    }
}


